<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>移动端文本播放器 - version:1.2</title>
    <style>
        :root {
            --primary-color: #2196F3;
            --bg-color: #000;
            --text-color: #FFEB3B;
            --recite-btn-bg: #616161; /* 开始背诵检查按钮深灰背景色 */
            --help-icon-color: #FF5722; /* 更改问号图标颜色，使其更醒目 */
        }

        html {
            font-size: 16px;
            -webkit-text-size-adjust: 100%;
            -ms-text-size-adjust: 100%;
        }

        body {
            margin: 0;
            padding: 1rem;
            background: #f5f5f5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        #text-container {
            flex: 1;
            background: var(--bg-color);
            color: var(--text-color);
            padding: 1rem;
            border-radius: 0.5rem;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            font-size: 1.2rem;
            line-height: 1.8;
            touch-action: manipulation; /* 允许手势操作 */
        }

        .controls {
            margin-top: 1rem;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 0.5rem;
        }

        .control-group {
            background: white;
            padding: 0.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: relative;
        }

        button {
            width: 100%;
            padding: 0.8rem;
            font-size: 1rem;
            border: none;
            border-radius: 0.25rem;
            background: var(--primary-color);
            color: white;
            touch-action: manipulation;
        }

        /* 修改开始背诵检查按钮颜色和背景色 */
        button[onclick="startRecite()"] {
            background: var(--recite-btn-bg);
        }

        /* 问号提示样式 */
        .help-icon {
            position: absolute;
            top: 50%;
            left: -20px;
            transform: translateY(-50%);
            color: var(--help-icon-color);
            cursor: pointer;
            font-size: 1.5rem; /* 增大问号图标大小 */
        }

        /* 朗诵按钮样式 */
        #recite-button {
            background: #4CAF50;
            margin-top: 0.5rem;
        }

        /* 新增跳到上一个和下一个按钮样式 */
        #next-button,
        #prev-button {
            margin-top: 0.5rem;
        }

        @media (orientation: landscape) {
            body {
                flex-direction: row;
                gap: 1rem;
            }
            #text-container {
                flex: 2;
            }
            .controls {
                flex: 1;
                margin-top: 0;
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 480px) {
            html {
                font-size: 14px;
            }
            .controls {
                grid-template-columns: 1fr;
            }
        }

        #recite-input {
            width: 100%;
            height: 100px;
            margin-top: 10px;
            padding: 5px;
            box-sizing: border-box;
        }

        #recite-result {
            margin-top: 10px;
        }

        /* 新增底部导航栏样式 */
        .bottom-nav {
            margin-top: 1rem;
            display: flex;
            flex-direction: column;
            background: white;
            padding: 0.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .bottom-nav a {
            color: var(--primary-color);
            text-decoration: none;
        }

        .bottom-nav label {
            margin-bottom: 0.5rem;
        }

        /* 自定义文本录入框样式 */
        #custom-text-input {
            width: 100%;
            height: 100px;
            margin-top: 10px;
            padding: 5px;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <div id="text-container">请加载文本文件...</div>

    <div class="controls">
        <div class="control-group">
            <span class="help-icon" onclick="showHelp('load-file')">?</span>
            <input type="file" id="fileInput" hidden accept=".txt">
            <button onclick="document.getElementById('fileInput').click()">📁 加载文件</button>
        </div>

        <div class="control-group">
            <span class="help-icon" onclick="showHelp('jump')">?</span>
            <input type="number" id="jumpInput" placeholder="输入跳转编号">
            <button onclick="jumpToSegment()">跳转</button>
        </div>

        <div class="control-group">
            <span class="help-icon" onclick="showHelp('recite-check')">?</span>
            <label for="custom-text-input">自定义文本录入</label>
            <textarea id="custom-text-input" placeholder="输入自定义比对文本"></textarea>
            <button onclick="startRecite()">开始背诵检查</button>
            <button id="recite-button" onclick="reciteText()" style="display: none;">朗诵</button>
        </div>

        <div class="control-group">
            <button id="playBtn" onclick="togglePlay()">▶ 播放</button>
            <button onclick="stopPlayback()">⏹ 停止</button>
            <button id="next-button" onclick="jumpToNext()">▶︎ 跳到下一个</button>
            <button id="prev-button" onclick="jumpToPrev()">◀︎ 跳到上一个</button>
        </div>
    </div>

    <textarea id="recite-input" placeholder="请输入背诵内容"></textarea>
    <button onclick="checkRecite()">提交检查</button>
    <div id="recite-result"></div>

    <!-- 新增底部导航栏 -->
    <div class="bottom-nav">
        <label>速度：<input type="range" id="speed" min="1" max="30" value="10"></label>
        <label>字体：<input type="range" id="fontSize" min="12" max="32" value="16"></label>
        <a href="home.html">更多背诵文本下载</a>
    </div>

    <script>
        (function () {
            const baseWidth = 375;
            const docEl = document.documentElement;

            function setRemUnit() {
                const clientWidth = Math.min(docEl.clientWidth, 768);
                const rem = (clientWidth / baseWidth) * 16;
                docEl.style.fontSize = rem + 'px';
            }

            setRemUnit();
            window.addEventListener('resize', setRemUnit);
            window.addEventListener('orientationchange', setRemUnit);
        })();

        let segments = [];
        let currentIndex = 0;
        let isPlaying = false;
        let rafId = null;
        let startTime;
        let fontSize = 16;

        // 保存历史记录
        function saveHistory(fileContent, index) {
            localStorage.setItem('lastFileContent', fileContent);
            localStorage.setItem('lastIndex', index);
        }

        // 加载历史记录
        function loadHistory() {
            const lastFileContent = localStorage.getItem('lastFileContent');
            const lastIndex = localStorage.getItem('lastIndex');
            if (lastFileContent && lastIndex) {
                parseContent(lastFileContent);
                currentIndex = parseInt(lastIndex);
                updateDisplay();
            }
        }

        // 页面加载时尝试加载历史记录
        window.addEventListener('load', loadHistory);

        document.getElementById('fileInput').addEventListener('change', function (e) {
            const file = e.target.files[0];
            const reader = new FileReader();

            reader.onload = function (e) {
                try {
                    parseContent(e.target.result);
                    currentIndex = 0;
                    updateDisplay();
                    saveHistory(e.target.result, currentIndex); // 保存新文件和初始位置
                } catch (error) {
                    alert('读取文件时出现错误，可能是编码问题：' + error.message);
                }
            };

            reader.onerror = function () {
                alert('读取文件时出现错误，请检查文件是否损坏。');
            };

            reader.readAsText(file, 'UTF-8');
        });

        function parseContent(text) {
            segments = text.split('\n').filter(line => line.trim()).map(line => {
                const [label, ...content] = line.split(':');
                return {
                    label: label.trim(),
                    content: content.join(':').trim()
                };
            });
        }

        function updateDisplay() {
            const container = document.getElementById('text-container');
            const segment = segments[currentIndex];

            container.innerHTML = `
                <div style="color:#888">${segment.label}</div>
                <div>${segment.content}</div>
            `;
            container.style.fontSize = fontSize + 'px';
            saveHistory(localStorage.getItem('lastFileContent'), currentIndex); // 保存当前播放位置
        }

        function playStep(timestamp) {
            if (!isPlaying) return;

            const speed = document.getElementById('speed').value;
            const duration = 1000 / speed * segments[currentIndex].content.length;

            if (performance.now() - startTime >= duration) {
                currentIndex = (currentIndex + 1) % segments.length;
                updateDisplay();
                startTime = performance.now();
            }

            rafId = requestAnimationFrame(playStep);
        }

        function togglePlay() {
            isPlaying = !isPlaying;
            document.getElementById('playBtn').textContent = isPlaying ? '⏸ 暂停' : '▶ 播放';

            if (isPlaying) {
                startTime = performance.now();
                rafId = requestAnimationFrame(playStep);
            } else {
                cancelAnimationFrame(rafId);
            }
        }

        document.getElementById('fontSize').addEventListener('input', function (e) {
            fontSize = parseInt(e.target.value);
            document.getElementById('text-container').style.fontSize = fontSize + 'px';
        });

        function jumpToSegment() {
            const input = document.getElementById('jumpInput').value;
            const targetLabel = `(${input}, ${parseInt(input) + 1}, ${parseInt(input) + 2})`;
            for (let i = 0; i < segments.length; i++) {
                if (segments[i].label === targetLabel) {
                    currentIndex = i;
                    updateDisplay();
                    return;
                }
            }
            alert('未找到对应的标号段落');
        }

        function startRecite() {
            document.getElementById('recite-input').value = '';
            document.getElementById('recite-result').innerHTML = '';
            document.getElementById('recite-input').style.display = 'block';
        }

        function preprocess(text) {
            return text.replace(/[\d()、。，：；？！“”‘’]/g, '').replace(/\s+/g, '');
        }

        function checkRecite() {
            const reciteInput = document.getElementById('recite-input').value;
            const customText = document.getElementById('custom-text-input').value;
            let currentSegment;

            if (customText) {
                currentSegment = customText;
            } else {
                currentSegment = segments[currentIndex].content;
            }

            const processedOriginal = preprocess(currentSegment);
            const processedInput = preprocess(reciteInput);

            let resultHtml = '';
            let i = 0, j = 0;
            while (i < processedOriginal.length || j < processedInput.length) {
                if (i < processedOriginal.length && j < processedInput.length && processedOriginal[i] === processedInput[j]) {
                    resultHtml += processedOriginal[i];
                    i++;
                    j++;
                } else if (i < processedOriginal.length && (j >= processedInput.length || processedOriginal[i]!== processedInput[j])) {
                    resultHtml += `<span style="background-color: green;">${processedOriginal[i]}</span>`;
                    i++;
                } else if (j < processedInput.length && (i >= processedOriginal.length || processedOriginal[i]!== processedInput[j])) {
                    resultHtml += `<span style="background-color: red;">${processedInput[j]}</span>`;
                    j++;
                }
            }

            document.getElementById('recite-result').innerHTML = `原文：${processedOriginal}<br>背诵结果：${resultHtml}`;
        }

        // 判断是否支持手势放大功能
        const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        if (isTouchDevice) {
            let startDistance;
            let startFontSize = fontSize;

            document.getElementById('text-container').addEventListener('touchstart', function (e) {
                if (e.touches.length === 2) {
                    const dx = e.touches[0].clientX - e.touches[1].clientX;
                    const dy = e.touches[0].clientY - e.touches[1].clientY;
                    startDistance = Math.sqrt(dx * dx + dy * dy);
                    startFontSize = fontSize;
                }
            });

            document.getElementById('text-container').addEventListener('touchmove', function (e) {
                if (e.touches.length === 2) {
                    const dx = e.touches[0].clientX - e.touches[1].clientX;
                    const dy = e.touches[0].clientY - e.touches[1].clientY;
                    const currentDistance = Math.sqrt(dx * dx + dy * dy);
                    const scaleFactor = currentDistance / startDistance;
                    fontSize = startFontSize * scaleFactor;
                    document.getElementById('text-container').style.fontSize = fontSize + 'px';
                }
            });
        }

        // 判断是否支持朗诵功能
        const isSpeechSupported = 'SpeechSynthesis' in window;
        if (isSpeechSupported) {
            document.getElementById('recite-button').style.display = 'block';
        }

        function reciteText() {
            if (isSpeechSupported) {
                const synth = window.speechSynthesis;
                const text = segments[currentIndex].content.replace(/[\d()]/g, '');
                const utterance = new SpeechSynthesisUtterance(text);
                synth.speak(utterance);
            }
        }

        function showHelp(type) {
            // 从外部文件 help.txt 读取帮助信息
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'help.txt', true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        const helpContent = xhr.responseText;
                        const lines = helpContent.split('\n');
                        let currentSection = '';
                        let helpText = '';
                        for (let line of lines) {
                            if (line.startsWith('[')) {
                                currentSection = line.slice(1, -1);
                            } else if (currentSection === type) {
                                helpText += line + '\n';
                            }
                        }
                        if (helpText) {
                            alert(helpText);
                        } else {
                            alert('未找到关于 ' + type + ' 的帮助信息。');
                        }
                    } else {
                        alert('无法读取帮助文件，请检查 help.txt 文件是否存在。');
                    }
                }
            };
            xhr.send();
        }

        function jumpToNext() {
            currentIndex = (currentIndex + 1) % segments.length;
            updateDisplay();
        }

        function jumpToPrev() {
            currentIndex = (currentIndex - 1 + segments.length) % segments.length;
            updateDisplay();
        }
    </script>
</body>

</html>    